package reflect;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URISyntaxException;

/**
 * 自动调用与当前类Test3在同一个包中这些类的公开的，无参的,名字里还有字母"s"的方法
 */
public class Test3 {
    public static void main(String[] args) throws Exception {
        Class cls = Test3.class;
        File dir = new File(cls.getResource(".").toURI());
        String packName = cls.getPackage().getName();
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File sub:subs){
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            className = packName+"."+className;
            Class c = Class.forName(className);
            Constructor con = c.getDeclaredConstructor();
            if(con.getModifiers()!=Modifier.PUBLIC){
                continue;
            }
            Object obj = c.newInstance();
            System.out.println(obj);
            Method[] methods = c.getDeclaredMethods();
            for(Method method:methods){
                if(method.getParameterCount()==0
                        &&
                        method.getModifiers()== Modifier.PUBLIC
                        &&
                        method.getName().contains("s")
                ){
                    System.out.println("自动调用的方法:"+method.getName());
                    method.invoke(obj);
                }
            }

        }

    }
}
